package com.hkfg.controller;

import com.hkfg.domain.Product;
import com.hkfg.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@CrossOrigin
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("/listImages")
    public ModelAndView list(Model model) {
        List<Product> lists = productService.list();
        ModelAndView mav = new ModelAndView();
        mav.addObject("lists", lists);
        mav.setViewName("list");
        System.out.println(lists);
        return mav;
    }

    /**
     * 保存图片
     * @param file
     * @param product
     * @param map
     * @return
     */
    @RequestMapping("/pic")
    public String save(MultipartFile file, Product product, ModelMap map) {
        try { // 返回值可能要改一下     还user_id没弄
            return productService.save(file, product, map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




    @PostMapping("/u/img")
    @ResponseBody
    public int test(MultipartFile file, HttpServletRequest request) throws IOException{
        String path = request.getSession().getServletContext().getRealPath("/images");
        System.out.println("路径："+path);

        String fileName = file.getOriginalFilename();
        System.out.println("文件名称"+fileName);

        File dir = new File(path, fileName);
        System.out.println("判断目录是否存在："+dir.exists());
        if(!dir.exists()){
            dir.mkdirs();
        }
//      MultipartFile自带的解析方法
        file.transferTo(dir);

        //这里我在拼接出我图片要显示的url
        String imageurl = "http://localhost:8081/images/"+fileName;
        productService.img(imageurl);
        //将数据库中信息更新
//        User bUser = new User();
////        bUser.setId(id);
//        bUser.setHeadpic(imageurl);
//        E3Result result = getUserInfoService.updateUser(bUser);
        //返回结果
        return productService.img(imageurl);
    }

}
